package com.example.chat.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.aode.common.bean.response.News;
import com.aode.utils.chat.FileUtils;
import com.example.chat.R;
import com.example.chat.adapter.ChatAdapter;
import com.example.chat.bean.Emojicon;
import com.example.chat.bean.Faceicon;
import com.example.chat.bean.Message;
import com.example.chat.emoji.DisplayRules;
import com.example.chat.interfaces.OnOperationListener;
import com.example.chat.widget.KJChatKeyboard;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 聊天主界面
 */
public class ChatActivity extends AppCompatActivity {

    public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0x1;

    private KJChatKeyboard box;
    private ListView mRealListView;

    List<Message> datas = new ArrayList<Message>();
    private News news;
    private ChatAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        //自定义控件
        box = (KJChatKeyboard) findViewById(R.id.chat_msg_input_box);
        //listview集合
        mRealListView = (ListView) findViewById(R.id.chat_listview);

        mRealListView.setSelector(android.R.color.transparent);
        news = (News) getIntent().getParcelableExtra("news");
        Log.e("TAG",news.toString());
        initMessageInputToolBox();
        initListView();
    }

    private void initMessageInputToolBox() {
        box.setOnOperationListener(new OnOperationListener() {
            @Override
            public void send(String content) {
                if(news!=null){
                    Message message = new Message(Message.MSG_TYPE_TEXT, Message.MSG_STATE_SUCCESS,
                            news.getFromUserNam(), news.getFromUserAvatar(), news.getToUserName(),
                            news.getToUserAvatar(), content, true, true, new Date().toString());
                    datas.add(message);
                    //将消息传入适配器当中
                    adapter.refresh(datas);
                    createReplayMsg(message);
                }

            }

            @Override
            public void selectedFace(Faceicon content) {
                if(news!=null){
                    Message message = new Message(Message.MSG_TYPE_FACE, Message.MSG_STATE_SUCCESS,
                            news.getFromUserNam(), news.getFromUserAvatar(), news.getToUserName(), news.getFromUserAvatar(), content.getPath(), true, true, new
                            Date().toString());
                    datas.add(message);
                    adapter.refresh(datas);
                    createReplayMsg(message);
                }
            }

            @Override
            public void selectedEmoji(Emojicon emoji) {
                box.getEditTextBox().append(emoji.getValue());
            }

            @Override
            public void selectedBackSpace(Emojicon back) {
                DisplayRules.backspace(box.getEditTextBox());
            }

            @Override
            public void selectedFunction(int index) {
                switch (index) {
                    case 0:
                        goToAlbum();
                        break;
                    case 1:
                        Toast.makeText(getApplication(), "跳转相机，只做演示", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        List<String> faceCagegory = new ArrayList<>();
        File faceList = new File("");
        if (faceList.isDirectory()) {
            File[] faceFolderArray = faceList.listFiles();
            for (File folder : faceFolderArray) {
                if (!folder.isHidden()) {
                    faceCagegory.add(folder.getAbsolutePath());
                }
            }
        }

        box.setFaceData(faceCagegory);
        mRealListView.setOnTouchListener(getOnTouchListener());
    }

    private void initListView() {
        /**
         * 初始化信息
         */
        if(news!=null&&news.getContent().size()>0&&!news.getContent().isEmpty()){
            for(int i = 0;i < news.getContent().size();i++){
                Message message = new Message(Message.MSG_TYPE_TEXT,
                Message.MSG_STATE_SUCCESS, news.getFromUserNam(), news.getFromUserAvatar(), news.getToUserName(), news.getToUserAvatar(),
                 news.getContent().get(i),
                news.getIsSend().get(i),
     true,news.getDate());
                datas.add(message);
            }
        }

        adapter = new ChatAdapter(this, datas, getOnChatItemClickListener());
        mRealListView.setAdapter(adapter);
    }

    private void createReplayMsg(Message message) {
        if(news!=null){
            final Message reMessage = new Message(message.getType(), Message.MSG_STATE_SUCCESS, news.getFromUserNam(),
                    news.getFromUserAvatar(), news.getToUserName(), news.getToUserAvatar(), message.getType() == Message.MSG_TYPE_TEXT ? "返回:"
                    + message.getContent() : message.getContent(), false,
                    true, new Date().toString());
            new Thread(() -> {
                try {
                    Thread.sleep(1000 * (new Random().nextInt(3) + 1));
                    runOnUiThread(() -> {
                        datas.add(reMessage);
                        adapter.refresh(datas);
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && box.isShow()) {
            box.hideLayout();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 跳转到选择相册界面
     */
    private void goToAlbum() {
        Intent intent;
        intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "选择图片"),
                REQUEST_CODE_GETIMAGE_BYSDCARD);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
      //反正我在这里调用就好了传递一些东西进去让他改变应该就可以了在这里调用initListView

        if (requestCode == REQUEST_CODE_GETIMAGE_BYSDCARD) {
            Uri dataUri = data.getData();
            if (dataUri != null) {
                if(news!=null){
                    File file = FileUtils.uri2File(ChatActivity.this, dataUri);
                    Message message = new Message(Message.MSG_TYPE_PHOTO, Message.MSG_STATE_SUCCESS,
                            news.getFromUserNam(), news.getFromUserAvatar(), news.getToUserName(),
                            news.getToUserAvatar(), file.getAbsolutePath(), true, true, new Date().toString());
                    datas.add(message);
                    adapter.refresh(datas);
                }

            }
        }
    }

    /**
     * 若软键盘或表情键盘弹起，点击上端空白处应该隐藏输入法键盘
     *
     * @return 会隐藏输入法键盘的触摸事件监听器
     */
    private View.OnTouchListener getOnTouchListener() {
        return new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                box.hideLayout();
                box.hideKeyboard(ChatActivity.this);
                return false;
            }
        };
    }

    /**
     * @return 聊天列表内存点击事件监听器
     */
    private OnChatItemClickListener getOnChatItemClickListener() {
        return new OnChatItemClickListener() {
            @Override
            public void onPhotoClick(int position) {
                Log.d("debug", datas.get(position).getContent() + "点击图片的");
                Toast.makeText(ChatActivity.this, datas.get(position).getContent() + "点击图片的", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTextClick(int position) {
            }

            @Override
            public void onFaceClick(int position) {
            }
        };
    }

    @Override
    protected void onDestroy() {
        //这里实施返回之后传值，然后插入到服务器中
        Log.e("TAG",datas.size()+"");
        Log.e("OnDestroy->TAG",datas.toString());
        List<News> newsList = new ArrayList<>();
        List<Boolean> booleans = new ArrayList<>();
        List<String> contents = new ArrayList<>();
        for(int i = 0;i < datas.size();i++){
            news = new News();
        }
        super.onDestroy();
    }

    /**
     * 聊天列表中对内容的点击事件监听
     */
    public interface OnChatItemClickListener {
        void onPhotoClick(int position);

        void onTextClick(int position);

        void onFaceClick(int position);
    }
}
